package com.moons.uvcdemo;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.media.AudioManager;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
//import android.support.annotation.RequiresApi;
//import android.support.v4.app.ActivityCompat;
//import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    Context context;
    boolean bLightOpen = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context = this;

        initView();

        SerialPortUtil.getInstance().
                setOnDataReceiveListener(
                        new SerialPortUtil.OnDataReceiveListener() {
                            @Override
                            public void onDataReceive(byte[] buffer, int size) {
                                Log.d(TAG, "buff=" + buffer);
                            }
                        }
                );

    }

    public void initView() {

        final Button rgb = findViewById(R.id.rgb_bt);
        rgb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(MainActivity.this, RgbActivity.class);
                //执行意图
                startActivity(intent);
            }
        });

        /*******     */
        final Button IR_bt = findViewById(R.id.IR_bt);
        IR_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(MainActivity.this, RgbActivity.class);
                //执行意图
                startActivity(intent);
            }
        });

        /****  打开白光灯（串口操作）   */
        final Button wLight_bt_open = findViewById(R.id.wLight_bt_open);
        wLight_bt_open.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openLight();
            }
        });

        /*****  关闭白光灯   */

        final Button wLight_bt_close = findViewById(R.id.wLight_bt_close);
        wLight_bt_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                closeLight();
            }
        });

        /*****   redLight  */
        final Button redLight_bt_open = findViewById(R.id.redLight_bt_open);
        redLight_bt_open.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

        /****** 屏幕检测    */
        final Button scressTest_bt = findViewById(R.id.scressTest_bt);
        scressTest_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(MainActivity.this, ScreenTestActivity.class);
                //执行意图
                startActivity(intent);

            }
        });

        /*****  背光调节（安卓通用接口）   *****/
        final Button backLight_bt = findViewById(R.id.backLight_bt);
        backLight_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                justLight();
            }
        });

        /*****  playAudio   *****/
        final Button playAudio_bt = findViewById(R.id.playAudio_bt);
        playAudio_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AudioManager audioManager = (AudioManager) MainActivity.this.getSystemService(
                        Context.AUDIO_SERVICE);
                if (audioManager != null) {
                    audioManager.playSoundEffect(AudioManager.FX_KEYPRESS_INVALID);
                } else {
                    Log.w(TAG, "=============Couldn't get audio manager");
                }
            }
        });

        /*****  以太网   *****/
        final TextView etho_result = findViewById(R.id.etho_result);
        final TextView etho_info = findViewById(R.id.etho_info);
        new Thread(new Runnable() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        etho_info.setText("mac:" + getMac("/sys/class/net/eth0/address") + "\n IP:" + getIpAddress("eth0"));

                    }
                });
            }
        }).start();
        final Button etho_bt = findViewById(R.id.etho_bt);
        etho_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        String result = pingHost("www.baidu.com");
                        if (result.contains("success")) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                  etho_result.setText("网络正常！");
//                                  etho_result.setTextColor(Color.RED);
                                }
                            });
                        }
                    }
                }).start();

            }
        });

        /*****  wifi   *****/
        final TextView wifi_result = findViewById(R.id.wifi_result);
        final TextView wifi_info = findViewById(R.id.wifi_info);
        new Thread(new Runnable() {
            @Override
            public void run() {
                setWifiApEnabled(false);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        wifi_info.setText("mac:" + getMac("/sys/class/net/wlan0/address"));
                    }
                });
            }
        }).start();
        final Button wifi_bt = findViewById(R.id.wifi_bt);
        wifi_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {

                    @Override
                    public void run() {
                        final String result = pingHost("www.baidu.com");
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    wifi_info.setText("mac:" + getMac("/sys/class/net/wlan0/address") + "\n IP:" + getIpAddress("wlan0"));
                                    if (result.contains("success")) {
                                        wifi_result.setText("网络正常！");
                                    }
                                }
                            });

                    }
                }).start();
            }
        });

        /*****  doorNO   *****/
        final Button doorNo_bt = findViewById(R.id.doorNo_bt);
        doorNo_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openDoorNO();
            }
        });

        /*****  DoorNC   *****/
        final Button doorNC_bt = findViewById(R.id.doorNC_bt);
        doorNC_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                closeDoorNO();
            }
        });

        /*****  pushOutNO   *****/
        final Button pushOutNO_bt = findViewById(R.id.pushOutNO_bt);
        pushOutNO_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pushOUTNO();
            }
        });

        /******     */
        final Button pushOutNC_bt = findViewById(R.id.pushOutNC_bt);
        pushOutNC_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pushOUTNC();
            }
        });

        /******    */
        final Button alarmHNO_bt = findViewById(R.id.alarmHNO_bt);
        alarmHNO_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alarmHightNO();
            }
        });

        /******     */
        final Button alarmHNC_bt = findViewById(R.id.alarmHNC_bt);
        alarmHNC_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alarmHightNC();
            }
        });


        /*******     */
        final Button alarmLNO_bt = findViewById(R.id.alarmLNO_bt);
        alarmLNO_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alarmLowNO();
            }
        });

        /*****     ********/
        final Button alarmLNC_bt = findViewById(R.id.alarmLNC_bt);
        alarmLNC_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alarmLowNC();
            }
        });

        /*****  照片注册   ********/
        final Button picShot_bt = findViewById(R.id.picShot_bt);
        picShot_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(MainActivity.this, RegisterActivity.class);
                //执行意图
                startActivity(intent);
            }
        });
        /*****   人脸注册  ********/
        final Button faceShot_bt = findViewById(R.id.faceShot_bt);
        faceShot_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(MainActivity.this, Register_MainActivity.class);
                //执行意图
                startActivity(intent);
            }
        });
        /*****  人脸识别（通过特征值文件计算相似度）  ********/
        final Button faceRegnize_bt = findViewById(R.id.faceRegnize_bt);
        faceRegnize_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(MainActivity.this, ShotRegisterActivity.class);
                //执行意图
                startActivity(intent);
            }
        });

    }

    public boolean setWifiApEnabled(boolean enabled) {
        WifiManager wifiManager = (WifiManager) MainActivity.this.getApplicationContext()
                .getSystemService(Context.WIFI_SERVICE);
        if (enabled) { // disable WiFi in any case
            // wifi和热点不能同时打开，所以打开热点的时候需要关闭wifi
            wifiManager.setWifiEnabled(false);
            System.out.println(TAG + ":关闭wifi");
        } else {
            wifiManager.setWifiEnabled(true);
        }
            return false;
    }

    //获取mac地址，系统接口 以太网 /sys/class/net/eth0/address wifi: /sys/class/net/wlan0/address
    public String getMac(String str) {
        try {
            return loadFileAsString(str).trim(); //字符串留空格会导致正则表达false
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "";
        }
    }

    public static String loadFileAsString(String filePath) throws java.io.IOException {
        StringBuffer fileData = new StringBuffer(1000);
        BufferedReader reader = new BufferedReader(new FileReader(filePath));
        char[] buf = new char[1024];
        int numRead = 0;
        while ((numRead = reader.read(buf)) != -1) {
            String readData = String.valueOf(buf, 0, numRead);
            fileData.append(readData);
        }
        reader.close();
        return fileData.toString();
    }

    public String getIpAddress(String interfaceName) {
        try {
            Enumeration<NetworkInterface> enNetworkInterface = NetworkInterface.getNetworkInterfaces(); //获取本机所有的网络接口
            while (enNetworkInterface.hasMoreElements()) {  //判断 Enumeration 对象中是否还有数据
                NetworkInterface networkInterface = enNetworkInterface.nextElement();   //获取 Enumeration 对象中的下一个数据
                if (!networkInterface.isUp()) { // 判断网口是否在使用
                    continue;
                }
                if (!interfaceName.equals(networkInterface.getDisplayName())) { // 网口名称是否和需要的相同
                    continue;
                }
                Enumeration<InetAddress> enInetAddress = networkInterface.getInetAddresses();   //getInetAddresses 方法返回绑定到该网卡的所有的 IP 地址。
                while (enInetAddress.hasMoreElements()) {
                    InetAddress inetAddress = enInetAddress.nextElement();
                    if (inetAddress instanceof Inet4Address) {  //判断是否未ipv4
                        return inetAddress.getHostAddress();
                    }
//                    判断未lo时
//                    if (inetAddress instanceof Inet4Address && !inetAddress.isLoopbackAddress()) {
//                        return inetAddress.getHostAddress();
//                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "error";

    }

    /********  *****/
    public void justLight() {
        ContentResolver resolver = context.getContentResolver();
        boolean automicBrightness = false;
        try {
            automicBrightness = Settings.System.getInt(resolver,
                    Settings.System.SCREEN_BRIGHTNESS_MODE) == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC;
        } catch (Settings.SettingNotFoundException e) {
            e.printStackTrace();
        }

        WindowManager.LayoutParams lp = this.getWindow().getAttributes();
        lp.screenBrightness = Float.valueOf(10) * (1f / 255f);
        this.getWindow().setAttributes(lp);
        greenHandle.postDelayed(mRunnable, 1000);
    }

    private Handler greenHandle = new Handler();
    //
    private Runnable mRunnable = new Runnable() {
        @Override
        public void run() {//
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    WindowManager.LayoutParams lp = MainActivity.this.getWindow().getAttributes();
                    lp.screenBrightness = Float.valueOf(255) * (1f / 255f);
                    MainActivity.this.getWindow().setAttributes(lp);
                }
            });
//            greenHandle.postDelayed(mRunnable, 1000);
        }
    };

    public static String pingHost(String str) {
        String resault = "";
        try {
            // TODO: Hardcoded for now, make it UI configurable
            Process p = Runtime.getRuntime().exec("/system/bin/ping -c 4 -w 100 " + str);
            //Process p = Runtime.getRuntime().exec("ping 192.168.1.111");
            int status = p.waitFor();
            InputStream input = p.getInputStream();
            BufferedReader in = new BufferedReader(new InputStreamReader(input));
            StringBuffer buffer = new StringBuffer();
            String line = "";
            while ((line = in.readLine()) != null) {
                buffer.append(line);
                Log.i("info", line);
            }

            if (status == 0) {
                //  mTextView.setText("success") ;
                resault = "success";
                Log.i("info", "success......");

            } else {
                resault = "faild";
                //  mTextView.setText("fail");
                Log.i("info", "failed......" + status + "...");
            }

        } catch (IOException e) {
            //  mTextView.setText("Fail: IOException"+"\n");
        } catch (InterruptedException e) {
            //  mTextView.setText("Fail: InterruptedException"+"\n");
        }

        return resault;
    }

    public void watchDog() {
        byte[] buffer = new byte[9];
        int len = 0;
        buffer[0] = 0x55;
        buffer[1] = 0x55;
        buffer[2] = 0x00;
        buffer[3] = 0x54;
        buffer[4] = (byte) 0x01;//主机自定义数据
        buffer[5] = (byte) 0x02;//主机自定义数据
        buffer[6] = (byte) 0xff;
        buffer[7] = (byte) 0xf5;
        buffer[8] = (byte) 0xf5;
        SerialPortUtil.getInstance().sendBuffer(buffer);
        Log.d(TAG, "send watch dog - " + (len == buffer.length));
    }

    public void openLight() {  //打开补光灯
//        if (bLightOpen)
//            return;
        Log.d(TAG, "openLight: ");
        sendLight(true);
        bLightOpen = true;
    }

    private void sendLight(boolean bopen) {

        byte[] buffer = new byte[9];
        int len;
        buffer[0] = 0x55;
        buffer[1] = 0x55;
        buffer[2] = 0x00;
        buffer[3] = 0x33;
        buffer[4] = (byte) 0x01;
        buffer[5] = (byte) 0xff;
        buffer[6] = (byte) 0x33;
        buffer[7] = (byte) 0xf5;
        buffer[8] = (byte) 0xf5;
        SerialPortUtil.getInstance().sendBuffer(buffer);

    }

    private void closeLight() {

        byte[] buffer = new byte[9];
        int len;
        buffer[0] = 0x55;
        buffer[1] = 0x55;
        buffer[2] = 0x00;
        buffer[3] = 0x33;
        buffer[4] = (byte) 0x00;
        buffer[5] = (byte) 0xff;
        buffer[6] = (byte) 0xff;
        buffer[7] = (byte) 0xf5;
        buffer[8] = (byte) 0xf5;
        SerialPortUtil.getInstance().sendBuffer(buffer);

    }

    private void openDoorNO() {
        byte[] buffer = new byte[9];
        int len;
        buffer[0] = 0x55;
        buffer[1] = 0x55;
        buffer[2] = 0x00;
        buffer[3] = 0x31;
        buffer[4] = (byte) 0xff;
        buffer[5] = (byte) 0xff;
        buffer[6] = (byte) 0x2f;
        buffer[7] = (byte) 0xf5;
        buffer[8] = (byte) 0xf5;
        SerialPortUtil.getInstance().sendBuffer(buffer);
    }

    private void closeDoorNO() {
        byte[] buffer = new byte[9];
        int len;
        buffer[0] = 0x55;
        buffer[1] = 0x55;
        buffer[2] = 0x00;
        buffer[3] = 0x31;
        buffer[4] = (byte) 0x00;
        buffer[5] = (byte) 0xff;
        buffer[6] = (byte) 0x30;
        buffer[7] = (byte) 0xf5;
        buffer[8] = (byte) 0xf5;
        SerialPortUtil.getInstance().sendBuffer(buffer);
    }

    private void pushOUTNO() {
        byte[] buffer = new byte[9];
        int len;
        buffer[0] = 0x55;
        buffer[1] = 0x55;
        buffer[2] = 0x00;
        buffer[3] = 0x40;
        buffer[4] = (byte) 0x01;
        buffer[5] = (byte) 0x00;
        buffer[6] = (byte) 0xff;
        buffer[7] = (byte) 0xf5;
        buffer[8] = (byte) 0xf5;
        SerialPortUtil.getInstance().sendBuffer(buffer);
    }

    private void pushOUTNC() {
        byte[] buffer = new byte[9];
        int len;
        buffer[0] = 0x55;
        buffer[1] = 0x55;
        buffer[2] = 0x00;
        buffer[3] = 0x40;
        buffer[4] = (byte) 0x01;
        buffer[5] = (byte) 0x01;
        buffer[6] = (byte) 0xff;
        buffer[7] = (byte) 0xf5;
        buffer[8] = (byte) 0xf5;
        SerialPortUtil.getInstance().sendBuffer(buffer);
    }

    private void alarmHightNO() {
        byte[] buffer = new byte[9];
        int len;
        buffer[0] = 0x55;
        buffer[1] = 0x55;
        buffer[2] = 0x00;
        buffer[3] = 0x40;
        buffer[4] = (byte) 0x02;
        buffer[5] = (byte) 0x00;
        buffer[6] = (byte) 0xff;
        buffer[7] = (byte) 0xf5;
        buffer[8] = (byte) 0xf5;
        SerialPortUtil.getInstance().sendBuffer(buffer);
    }

    private void alarmHightNC() {
        byte[] buffer = new byte[9];
        int len;
        buffer[0] = 0x55;
        buffer[1] = 0x55;
        buffer[2] = 0x00;
        buffer[3] = 0x40;
        buffer[4] = (byte) 0x02;
        buffer[5] = (byte) 0x01;
        buffer[6] = (byte) 0xff;
        buffer[7] = (byte) 0xf5;
        buffer[8] = (byte) 0xf5;
        SerialPortUtil.getInstance().sendBuffer(buffer);
    }

    private void alarmLowNO() {
        byte[] buffer = new byte[9];
        int len;
        buffer[0] = 0x55;
        buffer[1] = 0x55;
        buffer[2] = 0x00;
        buffer[3] = 0x40;
        buffer[4] = (byte) 0x03;
        buffer[5] = (byte) 0x00;
        buffer[6] = (byte) 0xff;
        buffer[7] = (byte) 0xf5;
        buffer[8] = (byte) 0xf5;
        SerialPortUtil.getInstance().sendBuffer(buffer);
    }

    private void alarmLowNC() {
        byte[] buffer = new byte[9];
        int len;
        buffer[0] = 0x55;
        buffer[1] = 0x55;
        buffer[2] = 0x00;
        buffer[3] = 0x40;
        buffer[4] = (byte) 0x03;
        buffer[5] = (byte) 0x01;
        buffer[6] = (byte) 0xff;
        buffer[7] = (byte) 0xf5;
        buffer[8] = (byte) 0xf5;
        SerialPortUtil.getInstance().sendBuffer(buffer);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
//        libScreen.releaseCamera();
    }

    @Override
    protected void onResume() {

        super.onResume();
//        requestRecording();
        Log.e(TAG, "onResume: ===========");
    }

}
